<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据id" prop="dataId">
        <el-input
          v-model="queryParams.dataId"
          placeholder="请输入数据id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指标名字" prop="dataIndexName">
        <el-input
          v-model="queryParams.dataIndexName"
          placeholder="请输入指标名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数值" prop="dataNumber">
        <el-input
          v-model="queryParams.dataNumber"
          placeholder="请输入数值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文本值" prop="dataString">
        <el-input
          v-model="queryParams.dataString"
          placeholder="请输入文本值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据时间" prop="dataTime">
        <el-input
          v-model="queryParams.dataTime"
          placeholder="请输入数据记录时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          round
          icon="el-icon-message"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ruoyi-initialdata:initialdata:add']"
        >数据配置
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          round
          icon="el-icon-star-off"
          size="mini"
          @click="dataToIndex"
          v-hasPermi="['ruoyi-initialdata:initialdata:export']"
        >初始化指标表
        </el-button>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          round
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ruoyi-initialdata:initialdata:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          round
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi-initialdata:initialdata:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          round
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi-initialdata:initialdata:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          round
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ruoyi-initialdata:initialdata:export']"
          style="background-color: rebeccapurple;color: white"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="initialdataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="数据id" align="center" prop="dataId"/>
      <el-table-column label="指标名字" align="center" prop="dataIndexName"/>
      <el-table-column label="数据类型" align="center" prop="dataType"/>
      <el-table-column label="数值" align="center" prop="dataNumber"/>
      <el-table-column label="文本值" align="center" prop="dataString"/>
      <el-table-column label="数据记录时间" align="center" prop="dataTime"/>
      <el-table-column label="数据具体内容" align="center" prop="dataContent"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi-initialdata:initialdata:edit']"
            style="color: green;"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi-initialdata:initialdata:remove']"
            style="color: red;"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改原始数据信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据id" prop="dataId" v-show="this.title === '添加原始数据信息'">
          <el-input v-model="form.dataId" placeholder="请输入该条数据的id"/>
        </el-form-item>
        <el-form-item label="指标名字" prop="dataIndexName">
          <el-input v-model="form.dataIndexName" placeholder="请输入该条数据属于的指标名字"/>
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select v-model="form.dataType" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in dataTypeOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
          <el-icon :class="{'el-icon-info': form.dataType === '数字' || form.dataType === '字符串'}">
            <!-- 根据条件显示不同的图标 -->
          </el-icon>
          <span v-show="form.dataType === '数字'">如果类型是数字，则数值为数据的值，文本值为NULL</span>
          <span v-show="form.dataType === '字符串'">如果类型是字符串，则文本值为数据的值，数值为NULL</span>
        </el-form-item>
        <el-form-item label="数值" prop="dataNumber" v-show="form.dataType==='数字'">
          <el-input v-model="form.dataNumber" placeholder="请输入如果data类型是数字，则值为data的值，否则值为NULL"/>
        </el-form-item>
        <el-form-item label="文本值" prop="dataString" v-show="form.dataType==='字符串'">
          <el-input v-model="form.dataString" placeholder="请输入如果data类型是字符串，则值为data的值，否则值为NULL"/>
        </el-form-item>
        <el-form-item label="数据记录时间" prop="dataTime">
          <el-input v-model="form.dataTime" placeholder="请输入数据记录时间"/>
        </el-form-item>
        <el-form-item label="数据具体内容">
          <editor v-model="form.dataContent" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 原始数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <div class="upload-container">
        <div class="upload-select-wrapper">
        <span class="upload-label">选择文件类型：</span>
        <el-select v-model="upload.selectedType" placeholder="请选择文件类型" class="upload-select">
          <el-option label="sql" value="sql"></el-option>
          <el-option label="xlsx或xls" value="excel"></el-option>
          <el-option label="xml" value="xml"></el-option>
        </el-select>
        </div>
        <el-upload v-if="upload.selectedType !== ''"
                   ref="upload"
                   :limit="1"
                   :accept="acceptType"
                   :headers="upload.headers"
                   :action="upload.url + '?updateSupport=' + upload.updateSupport +'&selectedType='+upload.selectedType+'&isclearData='+upload.isclearData"
                   :disabled="upload.isUploading"
                   :on-progress="handleFileUploadProgress"
                   :on-success="handleFileSuccess"
                   :auto-upload="false"
                   drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新相同id的数据
            </div>
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.isclearData"/>
              是否清空已录入数据，替换为新数据
            </div>
            <span>仅允许导入{{ fileTypeDescription() }}格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate" v-show="upload.selectedType==='excel'">下载模板
            </el-link>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listInitialdata,
  getInitialdata,
  delInitialdata,
  addInitialdata,
  updateInitialdata, dataToIndex
} from "@/api/ruoyi-initialdata/initialdata";
import {getToken} from "@/utils/auth";

export default {
  name: "Initialdata",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 原始数据信息表格数据
      initialdataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dataId: null,
        dataIndexName: null,
        dataType: null,
        dataNumber: null,
        dataString: null,
        dataTime: null,
        dataContent: null
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 文件类型
        selectedType: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新相同id的数据
        updateSupport: false,
        // 是否清空已录入数据，替换为新数据
        isclearData:false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ruoyi-initialdata/initialdata/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dataId: [
          {required: true, message: "该条数据的指标id不能为空", trigger: "blur"}
        ],
        dataIndexName: [
          {required: true, message: "该条数据属于的指标名字不能为空", trigger: "blur"}
        ],
        dataType: [{
          required: true,
          message: '请选择下拉选择',
          trigger: 'change'
        }],
      },
      dataTypeOptions: [{
        "label": "数字",
        "value": "数字"
      }, {
        "label": "字符串",
        "value": "字符串"
      }],
    };
  },
  created() {
    this.getList();
  },
  computed: {
    acceptType() {
      switch (this.upload.selectedType) {
        case 'sql':
          return '.sql';
        case 'excel':
          return '.xls, .xlsx';
        case 'xml':
          return '.xml';
        default:
          return '';
      }
    }
  },
  methods: {
    /** 查询原始数据信息列表 */
    getList() {
      this.loading = true;
      listInitialdata(this.queryParams).then(response => {
        this.initialdataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dataId:null,
        dataIndexName: null,
        dataType: null,
        dataNumber: null,
        dataString: null,
        dataTime: null,
        dataContent: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加原始数据信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dataId = row.dataId || this.ids
      getInitialdata(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改原始数据信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataType === '字符串') {
            this.form.dataNumber = null;
          } else if (this.form.dataType === '数字') {
            this.form.dataString = null;
          }
          if (this.title === "修改原始数据信息") {
            updateInitialdata(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInitialdata(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dataIds = row.dataId || this.ids;
      this.$modal.confirm('是否确认删除原始数据信息编号为"' + dataIds + '"的数据项？').then(function () {
        return delInitialdata(dataIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ruoyi-initialdata/initialdata/export', {
        ...this.queryParams
      }, `initialdata_${new Date().getTime()}.xlsx`)
    },

    dataToIndex(){
      this.$confirm("是否确认初始化指标表？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用后端接口进行数据初始化
          this.dataToIndexRequest()
            .then(() => {
              this.$message.success("指标表初始化成功");
            })
            .catch((error) => {
              this.$message.error("指标表初始化失败: " + error.message);
            });
        })
        .catch(() => {
          this.$message.info("取消初始化指标表操作");
        });
    },
    dataToIndexRequest() {
      // 调用后端接口的方法，这里使用AjaxResult作为返回值
      return new Promise((resolve, reject) => {
        // 调用后端接口
        // 请确保在api/ruoyi-initialdata/initialdata.js中存在名为dataToIndex的方法
        dataToIndex()
          .then((response) => {
            // 请求成功，根据后端接口返回的数据进行处理
            if (response.code === 200) {
              resolve(response.data);
            } else {
              reject(new Error(response.msg || "请求失败"));
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "原始数据导入";
      this.upload.open = true;
    },

    /** 选中的文件类型 **/
    fileTypeDescription() {
      switch (this.upload.selectedType) {
        case 'sql':
          return 'sql';
        case 'excel':
          return 'xls、xlsx';
        case 'xml':
          return 'xml';
        default:
          return '';
      }
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('ruoyi-initialdata/initialdata/importTemplate', {}, `initialdata_example_${new Date().getTime()}.xlsx`)  // todo
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped>
.upload-container {
  margin-bottom: 10px;
}

.upload-select-wrapper {
  margin-bottom: 10px;
}

.upload-label {
  margin-right: 10px;
}

.upload-select {
  width: 150px;
}

</style>
